import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 给请求加token
    // 判断token不是空的时候才加token
    const _token = store.getters.token
    if (_token) {
      config.headers.Authorization = `Bearer ${_token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const { success, data, message } = response.data
    if (success) {
      return data
    } else {
      // 拿到了数据但是是错误的 给用户看一份 程序员看一份
      Message.error(message)
      return Promise.reject(new Error(message))
    }
  },
  error => {
    return Promise.reject(error)
  }
)

export default service
